import { NavBar, Image as MyImage } from "antd-mobile";
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import $fetch from "../../utils/app/$fetch";
import "./style.scss";

const TicketsPage = () => {
  const navigate: any = useNavigate();
  const location: any = useLocation();
  const goodsId = location?.state?.goodsId;
  const [ticketDetail, setTicketDetail] = useState<any>({});
  const [isLoaded, setLoaded] = useState(false);

  useEffect(() => {
    initPage();
  }, []);

  useEffect(() => {
    if (Object.keys(ticketDetail)?.length > 0) {
      const img: any = new Image();
      img.src = ticketDetail?.goodsPhoto;
    }
  }, [ticketDetail?.goodsPhoto]);

  const initPage = async () => {
    try {
      const res: any = await $fetch(
        `ticketHolder/ticketHolderDetail/${goodsId}`
      );
      setTicketDetail(res);
      setLoaded(true);
    } catch (error) {}
  };

  const back = () => {
    navigate("/home", { state: { current: "tickets" } });
  };

  const renderView = () => {
    if (!isLoaded) return null;
    return (
      <div className="that_tickets">
        <div className="public_wraper">
          {/* <img src={ticketDetail?.goodsPhoto} alt="" /> */}
          <MyImage
            src={ticketDetail?.goodsPhoto}
            fit="cover"
            height="100%"
            // width="4rem"
            // height="4rem"
            lazy={true}
            placeholder={<MyImage src="" width="100%" height="3.89rem" />}
          />
          <div className="footer">
            <div className="ticket">
              <div className="count">数量×{ticketDetail?.quantity}</div>
              <div>使用期限：{ticketDetail?.ticketTemVp}</div>
            </div>
            {ticketDetail?.ticketTemType !== "1" && (
              <div
                className="item_button"
                onClick={() =>
                  navigate("/coupon", {
                    state: {
                      ...ticketDetail,
                      from: "tickets",
                    },
                  })
                }
              >
                使用
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="container_tickets">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={back}
      >
        {ticketDetail?.goodsName}
      </NavBar>
      {renderView()}
    </div>
  );
};

export default TicketsPage;
